//
//  HSPDetailsViewController.m
//  Icar
//
//  Created by dllo on 15/10/19.
//  Copyright © 2015年 小龙侠. All rights reserved.
//

#import "HSPDetailsViewController.h"
#import "BaseHeader.h"
#import "AFNBlock.h"
#import "StringWithHeight.h"
#import "HSPDetailCollectionViewCell.h"
#import "HSPcommentViewController.h"
@interface HSPDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)NSMutableArray *detailsArray;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UILabel *labelPage;
@property (nonatomic,strong)UIView *titleView;
@property (nonatomic,strong)UIButton *imageButton;
@property (nonatomic,strong)UITableView *tableImageView;
@property (nonatomic,strong)UIButton *shareButton;
@property (nonatomic,strong)UIButton *downloadButton;
@property (nonatomic,strong)UIImageView *myImageView;
@property (nonatomic,strong)UIButton *commentsButton;
@property (nonatomic,copy)NSString *commentsStr;
@property (nonatomic,copy)NSString *changeStr;
@end

@implementation HSPDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _detailsArray = [[NSMutableArray alloc]init];
    _titleView = [[UIView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 64)];
    [_titleView setBackgroundColor:[UIColor blackColor]];
    UIImage *image1 = [UIImage imageNamed:@"5.png"];
    UIImage *img1 = [self scaleToSize:image1 size:CGSizeMake(30 * ADJUSTWIDTH, 30 * ADJUSTHEIGHT)];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(10 * ADJUSTWIDTH, 26 * ADJUSTHEIGHT, 80 * ADJUSTWIDTH, 35 * ADJUSTHEIGHT)];
    [backButton setImage:img1 forState:UIControlStateNormal];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backBack) forControlEvents:UIControlEventTouchUpInside];
    [_titleView addSubview:backButton];
    [self.view addSubview:_titleView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor blackColor];

//    _shareButton = [[UIButton alloc]initWithFrame:CGRectMake(ADJUSTWIDTH * 240, ADJUSTHEIGHT * 35, ADJUSTWIDTH * 80, ADJUSTHEIGHT * 20)];
//    [_shareButton setTitle:@"分享" forState:UIControlStateNormal];
//    [_shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [_shareButton addTarget:self action:@selector(shareChange:) forControlEvents:UIControlEventTouchUpInside];
//    [_titleView addSubview:self.shareButton];

    _imageButton = [[UIButton alloc]initWithFrame:CGRectMake(ADJUSTWIDTH * 300, ADJUSTHEIGHT * 35, ADJUSTWIDTH * 80, ADJUSTHEIGHT * 20)];
    [_imageButton setTitle:@"列表" forState:UIControlStateNormal];
    [_imageButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_imageButton addTarget:self action:@selector(iamgeChange:) forControlEvents:UIControlEventTouchUpInside];
    [_titleView addSubview:self.imageButton];
    
    [self creatImage];
    [self commentsCollection];
    
}
- (UIImage *)scaleToSize : (UIImage *)img size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (void)commentsCollection
{
    _commentsButton = [[UIButton alloc]initWithFrame:CGRectMake(ADJUSTWIDTH * 10, ADJUSTHEIGHT * 597, 100 * ADJUSTWIDTH, 30 * ADJUSTHEIGHT)];
    [_commentsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_commentsButton addTarget:self action:@selector(commentsChange) forControlEvents:UIControlEventTouchUpInside];
    NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *pathString = [documentString stringByAppendingString:@"ImgaeDetaaCo.plist"];
    if (ISCONENNCTED == YES) {
        [AFNBlock getDataWithString:[NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/cmt/get_newest_floor?url=http://beauty.pcauto.com.cn/photolist/%@.html",self.model.cid] block:^(id back) {
            self.commentsStr = [back objectForKey:@"total"];
            self.changeStr = [back objectForKey:@"id"];
            NSDictionary *dic2 = back;
            [dic2 writeToFile:pathString atomically:YES];
            if (self.commentsStr == nil) {
                [_commentsButton setTitle:@"无评论" forState:UIControlStateNormal];
            }
            else
            {
                [_commentsButton setTitle:[NSString stringWithFormat:@"评论 %@",self.commentsStr] forState:UIControlStateNormal];
            }
         
        }];
    }
    if (ISCONENNCTED == NO) {
        NSDictionary *dic1 = [NSDictionary dictionaryWithContentsOfFile:pathString];
        self.commentsStr = [dic1 objectForKey:@"total"];
        self.changeStr = [dic1 objectForKey:@"id"];
        NSLog(@"%@",dic1);
        if (self.commentsStr == nil) {
            [_commentsButton setTitle:@"无评论" forState:UIControlStateNormal];
        }
        else
        {
            [_commentsButton setTitle:[NSString stringWithFormat:@"评论 %@",self.commentsStr] forState:UIControlStateNormal];
        }
    }
     [self.view addSubview:self.commentsButton];
}
- (void)iamgeChange:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
      
        
        [UIView animateWithDuration:0.5 animations:^{
            _tableImageView.frame = CGRectMake(ADJUSTWIDTH * 245,  64, SCREEN_WIDTH * 130, ADJUSTHEIGHT * 603);
            _tableImageView.backgroundColor = [UIColor clearColor];
        }];
    }
    //弹出位置
    else
    {
        
        [UIView animateWithDuration:0.5 animations:^{
            _tableImageView.frame = CGRectMake(SCREEN_WIDTH,  ADJUSTHEIGHT *64, SCREEN_WIDTH * 130, SCREEN_HEIGHT * 603);
            [self.view bringSubviewToFront:_tableImageView];
        }];
        
    }
    
}
- (void)backBack
{
    [self.navigationController popViewControllerAnimated:YES];
    self.titleView.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)creatImage
{
    NSString *documentString = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSString *pathString = [documentString stringByAppendingString:@"ImgaeDetaa.plist"];
    if (ISCONENNCTED == YES) {
        [AFNBlock getDataWithString:[NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/photo/albums?modelId=%@",self.model.cid] block:^(id back) {
            self.detailsArray = [[NSMutableArray alloc] init];
            for (NSMutableDictionary *dic in [back objectForKey:@"photos"])
            {
                HSPImageAppreciate *model = [HSPImageAppreciate modelWithDictionary:dic];
                [self.detailsArray addObject:model];
                
            }
            [self creatCollection];
            [self creattable];
      [NSKeyedArchiver archiveRootObject:_detailsArray toFile:pathString];
        }];
    }
        if (ISCONENNCTED == NO) {
            //读取
    self.detailsArray = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:pathString]];
            [self creatCollection];
            [self creattable];
        }
    
   
}
- (void)creatCollection
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, ADJUSTHEIGHT * 467);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, ADJUSTHEIGHT * 500) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate =self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[HSPDetailCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.collectionView];
    self.labelPage = [[UILabel alloc]initWithFrame:CGRectMake(ADJUSTWIDTH * 310, ADJUSTHEIGHT * 597, 80 * ADJUSTWIDTH, 30 * ADJUSTHEIGHT)];
    self.labelPage.font = [UIFont systemFontOfSize:20. * ADJUSTWIDTH];
    self.labelPage.textColor = [UIColor whiteColor];
    [self.view addSubview:self.labelPage];
    
    _downloadButton = [[UIButton alloc]initWithFrame:CGRectMake(ADJUSTWIDTH * 150, ADJUSTHEIGHT * 597, 80 * ADJUSTWIDTH, 30 * ADJUSTHEIGHT)];
    [_downloadButton setTitle:@"下载" forState:UIControlStateNormal];
    [_downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_downloadButton addTarget:self action:@selector(downChange) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.downloadButton];
}
- (void)commentsChange
{
    HSPcommentViewController *pusj = [[HSPcommentViewController alloc]init];
    pusj.acceptStr = self.changeStr;
    pusj.modelImage = self.model;
    [self.navigationController pushViewController:pusj animated:YES];
}
- (void)downChange
{
     UIImageWriteToSavedPhotosAlbum(self.myImageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString *message;
    NSString *title;
    if (!error) {
        title = @"下载成功";
        message = @"已保存到本地";
    } else {
        title = @"下载失败";
        message = [error description];
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _detailsArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HSPDetailCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor blackColor];
    HSPImageAppreciate *model = self.detailsArray[indexPath.row];
    self.myImageView = [[UIImageView alloc] init];
    [self.myImageView sd_setImageWithURL:[NSURL URLWithString:model.url]placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    cell.labelImage.frame = CGRectMake(10 * ADJUSTWIDTH, ADJUSTHEIGHT * 250, ADJUSTWIDTH * 350, [StringWithHeight HeightWithText:model.desc width:ADJUSTWIDTH * 350 font:[UIFont systemFontOfSize:18. * ADJUSTWIDTH]]);
    [cell getimagePo:model];
    self.labelPage.text = [NSString stringWithFormat:@"%ld/%ld",indexPath.row + 1,self.detailsArray.count];
    return cell;
}
- (void)creattable
{
    _tableImageView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_HEIGHT, ADJUSTHEIGHT * 40, ADJUSTWIDTH * 130, ADJUSTHEIGHT * 603) style:UITableViewStylePlain];
    _tableImageView.delegate = self;
    _tableImageView.dataSource =self;
    _tableImageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableImageView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.detailsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85 * ADJUSTHEIGHT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HSPFirstCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell =[[HSPFirstCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    HSPImageAppreciate *data = [self.detailsArray objectAtIndex:indexPath.row];
    self.tableImageView.scrollsToTop = YES;
    [cell getlistImage:data];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH*indexPath.row, 0)animated:NO];
    self.labelPage.text = [NSString stringWithFormat:@"%ld/%ld",indexPath.row,self.detailsArray.count];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
